package com.example.wjy.fragments;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.example.onion.hxchat.util.PassWordHelp;
import com.example.room.entity.MyJoinTeam;
import com.example.superyi.myteam.R;
import com.example.superyi.myteam.databinding.FragmentMyJoinTeamBinding;
import com.example.wjy.adapter.MyJoinTeamAdapter;
import com.example.wjy.viewmodels.MyJoinTeamViewModel;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static com.example.wjy.MembersActivity.url;

/**
 * A simple {@link Fragment} subclass.
 * create an instance of this fragment.
 * 显示我加入的组队列表
 */
public class MyJoinTeamFragment extends Fragment {

    List<MyJoinTeam> teams;
    /**
     * The adapter of this RecyclerView.
     */
    MyJoinTeamAdapter adapter;

    /**
     * DataBinding of this fragment and fragment_my_create_team.
     */
    FragmentMyJoinTeamBinding binding;

    /**
     * ViewModel of this fragment with ViewModelStoreOwner MyTeamActivity.
     */
    MyJoinTeamViewModel model;

    /**
     * Constructs a fragment.
     */
    RecyclerView recyclerView;
    String userId;
    String url = "http://49.232.60.155:8080/AppServer_war/TeamServlet";

    public SwipeRefreshLayout swipeRefreshLayout;

    public MyJoinTeamFragment() {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_my_join_team,
                container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        model = new ViewModelProvider(requireActivity()).get(MyJoinTeamViewModel.class);

        //从masterViewModel中获取Livedata类型的数据列表
        adapter = new MyJoinTeamAdapter(model.getTeamListLive().getValue());

        //对该列表进行观察，一旦有变化，通知Recyclerview刷新界面
        model.getTeamListLive().observe(requireActivity(), teams -> {
            adapter.setTeamList(teams);
            adapter.notifyDataSetChanged();
        });

        recyclerView = binding.recyclerView;
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext(),
                LinearLayoutManager.VERTICAL, false));
        recyclerView.setAdapter(adapter);

        swipeRefreshLayout = binding.swipe;

        //不能删，但不知道为什么
        model.getTeamList().observe(requireActivity(), teams -> {
            adapter.setTeamList(teams);
            adapter.notifyDataSetChanged();
        });
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        userId = PassWordHelp.readPassword(requireActivity())[0];
        swipeRefreshLayout.setOnRefreshListener(() -> {

            new Thread(() -> {
                OkHttpClient client = new OkHttpClient();
                //传递的参数是以键值对传输的

                RequestBody requestBody = new FormBody.Builder()
                        .add("userId",userId)
                        .add("flag","5")
                        .add("userState","1")
                        .build();
                Request request = new Request.Builder()
                        .url(url)
                        .post(requestBody)
                        .build();
                Call call =  client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e) {

                    }

                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                        String json = response.body().string();
                        Gson gson = new Gson();
                        teams = gson.fromJson(json,new TypeToken<List<MyJoinTeam>>(){}.getType());
                        model.deleteAllTeam();
                        if(teams != null)
                            for(int i = 0;i < teams.size();++i)
                                model.insertTeam(teams.get(i));
                    }
                });

            }).start();

            swipeRefreshLayout.setRefreshing(false);
        });
    }
}